<template>
  <el-upload
    ref="uploadFile"
    class="upload_file"
    :action="action"
    :auto-upload="true"
    :show-file-list="false"
    :limit="1"
    :accept="formatFile"
    :before-upload="beforeUpload"
  >
    <!-- TODO 需要完整的样式设计 -->
    <template v-if="!file">
      <div v-if="defaultFile.name" class="file_name" :title="defaultFile.name" :style="{ width: fileWidth }">
        {{ defaultFile.name }}
      </div>
      <el-button v-else size="mini" type="default" icon="el-icon-upload2">点击上传</el-button>
    </template>
    <template v-else>
      <div class="file_name" :title="file.name" :style="{ width: fileWidth }">{{ file.name }}</div>
    </template>
  </el-upload>
</template>
<script>
import axios from 'axios';
import { getToken } from '@/lib/auth';
export default {
  name: 'UploadFile',
  props: {
    // 默认文件地址 - 可用于默认展示、图片回显、下载
    defaultFileUrl: {
      type: String,
      required: false,
      default: ''
    },
    // 默认文件名称 - 会覆盖通过文件地址转换的名称
    defaultFileName: {
      type: String,
      required: false,
      default: ''
    },
    // 是否立即上传
    isTimely: {
      type: Boolean,
      required: false,
      default: true
    },
    // 上传文件时显示文件名的最大宽度
    fileWidth: {
      type: String,
      required: false,
      default: '200px'
    },
    // 上传地址 - 完整的地址
    action: {
      type: String,
      required: true
    },
    // 上传文件展示类型 - 图片展示(image)/文件展示(file)
    fileType: {
      type: String,
      required: false,
      default: 'image'
    },
    // 文件最小限制 单位kb
    minSize: {
      type: Number,
      required: false,
      default: 0
    },
    // 文件最大限制 单位kb
    maxSize: {
      type: Number,
      required: false,
      default: 102400
    },
    // 文件类型 '.jpg,.png'
    formatFile: {
      type: String,
      required: false,
      default: '.jpg,.png'
    }
  },
  data() {
    return {
      file: '',
      uploadFormData: new FormData(),
      tokenInfo: getToken(),
      defaultFile: {}
    };
  },
  watch: {
    defaultFileUrl: {
      handler() {
        this.handleDefaultFile();
      }
    }
  },
  created() {
    this.handleDefaultFile();
  },
  methods: {
    init() {
      this.file = null;
      this.fileUrl = null;
    },
    // 处理传入默认文件显示
    handleDefaultFile() {
      // TODO
      this.defaultFile = {};
      if (!this.defaultFileUrl) return;
      const _defaultFileUrl = this.defaultFileUrl.split('/');
      const _name = _defaultFileUrl[_defaultFileUrl.length - 1];
      this.defaultFile = {
        name: this.defaultFileName || _name,
        url: this.defaultFileUrl
      };
    },
    beforeUpload(file) {
      console.log(file);
      if (this.maxSize && file.size > this.maxSize * 1024) {
        this.handleMaxSizeError(file);
        return false;
      }
      if (this.minSize && file.size < this.minSize * 1024) {
        this.handleMinSizeError(file);
        return false;
      }
      var _imgType = file.name.split('.');
      _imgType = _imgType[_imgType.length - 1];
      _imgType = _imgType && _imgType.toLowerCase();
      console.log(this.formatFile);
      if (this.formatFile.indexOf(_imgType) === -1) {
        this.handleFormatError(file);
        return false;
      }
      this.file = file;
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onloadend = () => {
        this.fileUrl = fileReader.result;
      };
      if (this.isTimely) {
        this.upload().then(res => {
          this.$emit('uploadSuccess', res);
        });
      }
      return false;
    },
    // 暴露在外面的上传
    upload() {
      return new Promise((resolve, reject) => {
        if (!this.file) {
          resolve('');
          return;
        }
        this.uploadFormData = new FormData();
        this.uploadFormData.append('formFile', this.file);
        this.uploadFile(this.action, this.uploadFormData).then(res => {
          if (res.status === 200) {
            resolve(res.data);
          } else {
            reject(res.data);
          }
        });
      });
    },
    // 文件大小错误
    handleMaxSizeError(file) {
      this.$message({
        type: 'error',
        showClose: true,
        message: '文件[' + file.name + ']太大，不能超过' + this.maxSize + 'kb。'
      });
    },
    handleMinSizeError(file) {
      this.$message({
        type: 'error',
        showClose: true,
        message: '文件[' + file.name + ']太小，不能小于' + this.minSize + 'kb。'
      });
    },
    // 文件格式错误
    handleFormatError(file) {
      this.$message({
        type: 'error',
        showClose: true,
        message: `文件[${file.name}]格式不正确，请上传 ${this.formatFile}格式的文件。`
      });
    },
    // 请求
    uploadFile(url, data) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, data, config);
    },
    stopPropagation(e) {
      if (e && e.stopPropagation) {
        e.stopPropagation();
      } else {
        window.event.cancelBubble = true;
      }
    }
  }
};
</script>
<style>
.upload_file .file_name {
  font-size: 12px;
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
  transition: all 0.1s ease;
}
.upload_file .file_name:hover {
  text-decoration: underline;
  color: #5cadff;
}
</style>
